package com.proj.service.impl;

import com.proj.beans.User;
import com.proj.dao.UserDao;
import com.proj.entities.UserEntity;
import com.proj.service.UserService;
import com.proj.service.assembler.UserAssembler;

import java.util.ArrayList;
import java.util.List;

public class UserServiceImpl implements UserService
{
    private UserDao userDao;

    public long createUser(User user)
    {
        if (user == null)
        {
            throw new IllegalArgumentException("User bean passed for create is null.");
        }
        if (user.getId() > 0)
        {
            throw new IllegalArgumentException("Id cannot be set by the user.");
        }

        UserEntity userEntity = UserAssembler.getUserEntity(user);
        return userDao.createUser(userEntity);
    }

    public User getUser(String userId)
    {
        UserEntity userEntity = userDao.getUser(userId);
        return UserAssembler.getUserBean(userEntity);
    }


    //todo:userName should be removed from the method signature
    public void updateUser(String userName, User user)
    {
        if (user == null || userName == null)
        {
            throw new IllegalArgumentException("userName of user is null");
        }

        if (!userName.equals(user.getUserName()))
        {
            throw new IllegalArgumentException("usernames dont match");
        }
        UserEntity userEntity = userDao.getUser(userName);
        userEntity.setFirstName(user.getFirstName());
        userEntity.setLastName(user.getLastName());
        userEntity.setAddress(user.getAddress());
        userEntity.setAge(user.getAge());
        userEntity.setEmail(user.getEmail());
        userEntity.setPhone(user.getPhone());
        userDao.updateUser(userEntity);
    }

    public void deleteUser(String userId)
    {
        System.out.println("Deleting user "+userId);
        userDao.deleteUser(userId);
    }

    public List<User> getAllUsers()
    {
        List<User> users = new ArrayList<User>();
        List<UserEntity> allUsers = userDao.getAllUsers();
        if (allUsers != null && !allUsers.isEmpty())
        {

            for (UserEntity user : allUsers)
            {
                users.add(UserAssembler.getUserBean(user));
            }
        }
        return users;
    }

    public void setUserDao(UserDao userDao)
    {
        this.userDao = userDao;
    }
}
